import {createAsyncThunk, createSlice} from "@reduxjs/toolkit";
import {getRouters} from "@/clientApi/system/menu";

const routerSlice = createSlice({
    name: 'route',
    initialState: {
        routerList: [],
        loading:true,
    },
    reducers: {
        SET_ROUTER: (state, {payload: routerList}) => {
            state.routerList=routerList
        },
        SET_LOADING: (state, {payload: loading}) => {
            state.loading=loading
        },
    },

    // https://zhuanlan.zhihu.com/p/382487951
    // 一般用于处理异步操作，这里是Pending: 当异步操作开始时，Fulfilled: 当异步操作成功完成时，Rejected: 当异步操作遇到错误时
    extraReducers: (builder) => {
        // builder.addCase(getUserInfoSlice.pending, () => {
        //     // console.log('pending 进行中');
        // })
        // builder.addCase(getUserInfoSlice.fulfilled, (state, { payload }) => {
        //     // console.log( '1 fulfilled', { payload, state } )
        // })
        // builder.addCase(getUserInfoSlice.rejected, (state, action) => {
        //     // userSlice.actions.CLEAR_USER_INFO()
        // })
    }


})

export const {SET_ROUTER,SET_LOADING} = routerSlice.actions


export const getRouterRX = createAsyncThunk("user/getRouter",
    async (_, thunkAPI) => {

        try {
            thunkAPI.dispatch(SET_LOADING(true))
            const res:any = await getRouters()
            if (res.code === 200) {
                thunkAPI.dispatch(SET_ROUTER(JSON.parse(JSON.stringify(res.data)) ))
                thunkAPI.dispatch(SET_LOADING(false))
            } else if(res.code===401) {
                thunkAPI.dispatch(SET_LOADING(false))
                // AntMessage.warning(msg || '登录失败')
            }
        } catch (error) {
            console.log(error, 'error')
        }
    })





const routeReducer = routerSlice.reducer
export default routeReducer
